%%%-------------------------------------------------------------------
%% @doc chat channel supervisor.
%% @end
%%%-------------------------------------------------------------------

-module(chat_channel_sup).

-behaviour(supervisor).

-export([ start_link/1
        , init/1
        ]).

-export([ start_channel/2 
        , find_channel/1
        ]).


start_link(Config) ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, [Config]).

%% sup_flags() = #{strategy => strategy(),         % optional
%%                 intensity => non_neg_integer(), % optional
%%                 period => pos_integer()}        % optional
%% child_spec() = #{id => child_id(),       % mandatory
%%                  start => mfargs(),      % mandatory
%%                  restart => restart(),   % optional
%%                  shutdown => shutdown(), % optional
%%                  type => worker(),       % optional
%%                  modules => modules()}   % optional
init([_Config]) ->
    SupFlags = 
        #{ strategy     => one_for_one
         , intensity    => 0
         , period       => 1
         },
    ChildSpecs = [ ],
    {ok, {SupFlags, ChildSpecs}}.


start_channel(Config, Channel) ->
    Worker = #{ id => {chat_channel, Channel}
              , start => {chat_channel_worker, start_link, [{Config, Channel}]}
              , restart => temporary
              , shutdown => 5000
              , type => worker
              , modules => [chat_channel_worker]
              },
    supervisor:start_child(?MODULE, Worker).


find_channel(Channel) ->
    ChildId = {chat_channel, Channel},
    ChildList = supervisor:which_children(?MODULE),
    find_child(ChildId, ChildList).

find_child(ChildId, [{ChildId, Pid, _, _} | _]) ->
    Pid;
find_child(_, []) ->
    undefined;
find_child(ChildId, [_ | ChildList]) ->
    find_child(ChildId, ChildList).



%% internal functions
